from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
from sqlalchemy import create_engine, Table, MetaData, Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker

# 连接到Elasticsearch
es = Elasticsearch(['http://10.10.3.183:19200/'])

# 连接到数据库
engine = create_engine('oracle://operation:operation@10.10.3.34:1521/operation')
Session = sessionmaker(bind=engine)
session = Session()

# 定义Elasticsearch文档映射到数据库表的模型
metadata = MetaData()
elastic_table = Table('elastic_table', metadata,
                      Column('id', Integer, primary_key=True),
                      Column('name', String),
                      Column('age', Integer))

# 查询Elasticsearch
# s = Search(using=es, index='user-operation-log').query('match_all')
s = Search(using=es, index='user-operation-log').execute()
print(s.to_dict())
for doc in s.scan():
    # 转换数据（从Elasticsearch的结构转换到数据库模型）
    data = {
        'id': doc.meta.id,
        'name': doc.name,
        'age': doc.age
    }

    # 将数据插入到数据库
    session.execute(elastic_table.insert().values(**data))
    session.commit()

session.close()